package com.typ.member.web.api;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.typ.member.common.model.PageRequest;
import com.typ.member.common.model.Response;
import com.typ.member.common.model.ResponseUtil;
import com.typ.member.dao.model.MemberTradeDto;
import com.typ.member.dao.model.MemberTradeQueryDto;
import com.typ.member.service.MemberTradeService;
import com.typ.member.web.model.MemberTradeQueryVo;
import com.typ.member.web.model.MemberTradeVo;
import com.typ.member.web.model.MemberTradeQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员卡信息API
 *
 * @author heran
 * @version 1.0, 2019-05-09 18:09
 */
@RestController
@Slf4j
@RequestMapping("/api/member/trade")
public class MemberTradeApiController {

    @Resource
    private MemberTradeService memberTradeService;

    @SuppressWarnings("Duplicates")
    @GetMapping("/search")
    public Response search(@ModelAttribute MemberTradeQueryVo memberTradeQueryVo, @ModelAttribute PageRequest pageRequest) {
        MemberTradeQueryDto memberTradeQueryDto = translateMemberTradeQueryVo(memberTradeQueryVo);
        PageInfo<MemberTradeDto> pageInfo = memberTradeService.search(memberTradeQueryDto, pageRequest);
        PageInfo<MemberTradeVo> result = new PageInfo<>();
        BeanUtils.copyProperties(pageInfo, result);
        result.setList(convert2MemberTradeVoList(pageInfo.getList()));
        return ResponseUtil.createSuccess(result);
    }

    private List<MemberTradeVo> convert2MemberTradeVoList(List<MemberTradeDto> memberTradeDtos) {
        if (CollectionUtils.isEmpty(memberTradeDtos)) {
            return Lists.newArrayList();
        }
        return memberTradeDtos.stream().map(memberTradeDto -> {
            MemberTradeVo memberTradeVo = new MemberTradeVo();
            BeanUtils.copyProperties(memberTradeDto, memberTradeVo);
            return memberTradeVo;
        }).collect(Collectors.toList());
    }

    private MemberTradeQueryDto translateMemberTradeQueryVo(MemberTradeQueryVo input) {
        if (input == null) {
            return null;
        }
        MemberTradeQueryDto result = new MemberTradeQueryDto();
        result.setId(input.getId());
        result.setCardId(input.getCardId());
        result.setName(input.getName());
        result.setPhone(input.getPhone());
        result.setOpType(input.getOpType());
        result.setModified(input.getModified());
        if (input.getModifiedEnd() != null) {
            result.setModifiedEnd(new Date(input.getModifiedEnd()));
        }
        if (input.getModifiedStart() != null) {
            result.setModifiedStart(new Date(input.getModifiedStart()));
        }
        return result;
    }

}
